package com.whq.thrift.api.web.admin.controller.bs.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.whq.common.StringUtil;
import com.whq.thrift.api.web.admin.db.admin.PermissionUri;
import com.whq.thrift.api.web.admin.db.admin.UserInfo;
import com.whq.thrift.api.web.admin.db.admin.UserMermission;
import com.whq.thrift.api.web.admin.service.admin.PermissionUriService;
import com.whq.thrift.api.web.admin.util.PageData;

@Controller
@Scope("prototype")
public class PermissionUriController {
	private static final int DEFAULT_PAGE_SIZE = 25;
	
	@Autowired
	private PermissionUriService permissionUriService;
	
	@RequestMapping(value="bs/admin/permission/list")
	public String list(
			@RequestParam(value="permissionId",required=false) String permissionId ,
			@RequestParam(value="uri",required=false) String uri,
			@RequestParam(value="module",required=false) String module,
			@RequestParam(value = "currentPage", required = true, defaultValue = "1") Integer currentPage,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,Model model ){
		PageData<PermissionUri> pageData = new PageData<PermissionUri>();
		pageData.setCurrentPage(currentPage);
		if ((pageSize == null) || (pageSize <= 0)) {
			pageSize = DEFAULT_PAGE_SIZE;
		}
		pageData.setPageSize(pageSize);
		
		// 查询参数
		Map<String, Object> whereParams = new HashMap<String, Object>(0);
		if(StringUtil.isNotBlank(permissionId)){
			whereParams.put("permissionId", permissionId);
		}
		if(StringUtil.isNotBlank(uri)){
			whereParams.put("uri", uri);
		}
		if(StringUtil.isNotBlank(module)){
			whereParams.put("module", module);
		}
		
		int count = this.permissionUriService.findRecordCount(whereParams);
		pageData.setTotalCount(count);

		int beginIndex = (currentPage - 1) * pageSize;
		List<PermissionUri> resultList = this.permissionUriService.findRecordsByMap(whereParams, beginIndex, pageSize);
		pageData.setResultList(resultList);

		model.addAttribute("permissionId", permissionId);
		model.addAttribute("uri", uri);
		model.addAttribute("module", module);
		model.addAttribute("pageData", pageData);

		return "bs/admin/permission/list";
	}
	
	@RequestMapping(value = "bs/admin/permission/show")
	public String show(@RequestParam(value = "id", required = true) String id, Model model) {
		if (id == null) {
			return "error";
		}
		PermissionUri record = this.permissionUriService.findRecordById(id);
		model.addAttribute("record", record);
		if (record == null) {
			return "error";
		}
		return "bs/admin/permission/show";
	}
	
	@RequestMapping(value="bs/admin/permission/showAdd")
	public String showAdd(Model model){
		PermissionUri record = new PermissionUri();
		model.addAttribute("record", record);
		return "bs/admin/permission/showAdd";
	}
	
	@RequestMapping(value="bs/admin/permission/add")
	public String add(@Valid PermissionUri record, 
			BindingResult result, 
			Model model) {
		PermissionUri existRecord = this.permissionUriService.findRecordByUri(record.getUri());
		if (existRecord != null) {
			model.addAttribute("errMsg", "Uri已存在，不能重复！！");
			model.addAttribute("record", record);
			return "bs/admin/permission/showAdd";
		}
		
		this.permissionUriService.addRecord(record);
		return "redirect:show.do?id=" + record.getPermissionId();
	}
	
	@RequestMapping(value="bs/admin/permission/showUpd")
	public String showUpd(@RequestParam(value="id", required=true) String id, 
			Model model){
		if (id == null) {
			return "error";
		}
		PermissionUri record = this.permissionUriService.findRecordById(id);
		if (record == null) {
			return "error";
		}
		model.addAttribute("record", record);
		return "bs/admin/permission/showUpd";
	}
	
	@RequestMapping(value="bs/admin/permission/upd")
	public String upd(@Valid PermissionUri record, 
			BindingResult result, Model model) {
		if (result.hasErrors()) {
			model.addAttribute("record", record);
			return "bs/admin/permission/showUpd";
		}
		
		this.permissionUriService.updateRecord(record);
		return "redirect:show.do?id=" + record.getPermissionId();
	}
	
	@RequestMapping(value="bs/admin/permission/del")
    public String del(@RequestParam(value = "id", required = true, defaultValue = "0") String id,
            Model model) {
        this.permissionUriService.deleteRecord(id);
        return "bs/admin/permission/delOk";
    }
	
	@RequestMapping(value="bs/admin/permission/delRecords")
    public String delRecords(String[] delIds,
            Model model) {
        if (delIds != null) {
            for (int i = 0; i < delIds.length; i++) {
                if (delIds[i] != null) {
                    this.permissionUriService.deleteRecord(delIds[i]);
                }
            }
        }
        return "redirect:list.do";
    }
	
	@RequestMapping(value = "bs/admin/permission/permissionlist")
	public String permissionlist(@RequestParam(value = "id", required = true) String id, Model model) {
		if (id == null) {
			return "error";
		}

		List<UserMermission> userList = this.permissionUriService.findUserMermissionById(id);

		List<UserInfo> resultList = this.permissionUriService.findUserInfoByMap();

		List<String> tempList = new ArrayList<String>();
		for (int i = 0; i < userList.size(); i++) {
			tempList.add(userList.get(i).getEmail());
		}

		// 比较如果有相同的permissionid则checked设为true
		if (userList != null) {
			for (UserInfo pUri : resultList) {
				if (tempList.contains(pUri.getEmail())) {
					pUri.setChecked(true);
				} else {
					pUri.setChecked(false);
				}
			}
		}

		model.addAttribute("permissionId", id);
		model.addAttribute("record", resultList);
		return "bs/admin/permission/permissionlist";
	}
	
	@RequestMapping(value = "bs/admin/permission/updUserMerssion.do")
	public String updUserMerssion(String[] updEmails, @RequestParam(value = "id", required = false) String id, Model model) {
		this.permissionUriService.delUserPermission(id);
		List<UserMermission> userList = this.permissionUriService.findUserMermissionById(id);
		if (userList != null) {
			model.addAttribute("errMsg", "权限已存在");
		}

		if (updEmails != null) {
			for (int i = 0; i < updEmails.length; i++) {
				UserMermission record = new UserMermission();
				record.setEmail(updEmails[i]);
				record.setPermissionId(Integer.valueOf(id));
				if (record != null) {
					this.permissionUriService.addUserMermission(record);
				}
			}
		}else{
			this.permissionUriService.delUserPermission(id);
		}
		return "redirect:permissionlist.do?id="+id;
	}
}
